<?php
if (!$in_index)
{
	die();
}

class sql_db
{
	private $db_connect;
	private $query_result;
	private $row = array();
	private $rowset = array();
	private $num_queries;
	private $in_transaction = 0;

	public function __construct()
	{
		$this->connectDb();
	}

	private function connectDb() {
		$this->db_connect = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD);

		if ($this->db_connect)
		{
			$gotdb = mysql_select_db(DATABASE);
			if (!$gotdb)
			{
				// connection to database failed, close connection
				mysql_close($this->db_connect);
				$this->db_connect = $gotdb;
			}

			// Send back value of connection attempt
			return $this->db_connect;
		} else {
			// Could not connect to MySQL server
			return false;
		}
	}

	public function __destruct()
	{
		$this->sql_close();
	}

	private function sql_close()
	{
		// Make sure we're connected before trying to disconnect
		if ($this->db_connect)
		{
			// See if we're in the middle of something
			if ($this->in_transaction)
			{
				mysql_query("COMMIT", $this->db_connect);
			}

			// Connection closed
			return mysql_close($this->db_connect);
		} else {
			// No connection was open; nothing to close.
			return false;
		}
	}

	public function doQuery($query)
	{
		// Clear any queries currently stored
		unset($this->query_result);

		$this->num_queries++;
		$this->query_result = mysql_query($query, $this->db_connect);

		if ($this->query_result)
		{
			unset($this->row[$this->query_result]);
			unset($this->rowset[$this->query_result]);

			return $this->query_result;
		} else {
			return false;
		}
	}

	public function sql_numrows($query_id = 0)
	{
		if (!$query_id)
		{
			$query_id = $this->query_result;
		}

		return ($query_id) ? mysql_num_rows($query_id) : false;
	}

	public function sql_affectedrows()
	{
		return ($this->db_connect) ? mysql_affected_rows($this->db_connect) : false;
	}

	public function sql_nextid()
	{
		return ($this->db_connect) ? mysql_insert_id($this->db_connect) : false;
	}

	public function sql_freeresult($query_id = 0)
	{
		if (!$query_id)
		{
			$query_id = $this->query_result;
		}

		if ($query_id)
		{
			unset($this->row[$query_id]);
			unset($this->rowset[$query_id]);
			mysql_free_result($query_id);

			return true;
		} else {
			return false;
		}
	}

	public function sql_error()
	{
		$result['message'] = mysql_error($this->db_connect);
		$result['code'] = mysql_errno($this->db_connect);

		return $result;
	}

	public function getId()
	{
		return mysql_insert_id($this->db_connect);
	}
}

?>
